package jnpf.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jnpf.base.ActionResult;
import jnpf.common.enums.dify.DifyAITypeEnum;
import jnpf.common.enums.dify.DifyApiEnum;
import jnpf.entity.AgentEntity;
import jnpf.entity.KnowMangeEntity;
import jnpf.model.dify.file.req.CreateDocumentReq;
import jnpf.model.dify.file.req.CreateSegmentsReq;
import jnpf.model.dify.file.req.UpdateSegmentReq;
import jnpf.model.dify.know.req.CreateDataSetsReq;
import jnpf.model.external.CreateMetadata;
import jnpf.model.external.DifyAiCreateReq;
import jnpf.model.external.DifyAiUpdateReq;
import jnpf.model.knowcreate.KnowCreate;
import jnpf.model.objRelation.ModelListResp;
import jnpf.model.objRelation.RagGraphResponse;
import jnpf.model.ragFlow.common.RagFlowApiResult;
import jnpf.model.ragFlow.know.CreateKnowReq;
import jnpf.model.ragFlow.know.DatasetResp;
import jnpf.model.ragFlow.know.api.AssistantConfig;
import jnpf.model.ragFlow.know.api.AssistantConfigReq;
import jnpf.model.ragFlow.know.api.AssistantConfigResp;
import jnpf.model.ragFlow.know.api.AssistantDeleteReq;
import jnpf.model.ragFlow.knowApiCreate.UpdateKnowReq;
import jnpf.service.AgentService;
import jnpf.service.DifyKnowService;
import jnpf.service.ExternalLoginService;
import jnpf.service.KnowMangeService;
import jnpf.util.DifyApiReqUtil;
import jnpf.util.UserProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.*;

import static jnpf.util.ResultHandleUtil.txtConvertObj;

@Service
public class DifyKnowServiceImpl implements DifyKnowService {
    @Value("${dify.url}")
    public String API_BASE_URL;
    @Value("${dify.knowApiKey}")
    public String API_KEY;
    @Autowired
    UserProvider userProvider;
    @Value("${login.dify.url:}")
    private String DIFY_URL;
    @Value("${login.rag.url:}")
    private String RAG_URL;
    @Autowired
    private ExternalLoginService externalLoginService;
    @Autowired
    private AgentService agentService;
    @Autowired
    private KnowMangeService knowMangeService;


    @Override
    public String createEmptyDataset(CreateDataSetsReq createDataSetsReq) throws Exception {
        return DifyApiReqUtil.sendApiReq(API_BASE_URL, API_KEY, DifyApiEnum.CREATE_EMPTY_DATASET, new HashMap<>(), createDataSetsReq, userProvider.get().getUserId());
    }

    @Override
    public String createDocumentByText(String datasetId, CreateDocumentReq requestBody) throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put("dataset_id", datasetId);
        return DifyApiReqUtil.sendApiReq(API_BASE_URL, API_KEY, DifyApiEnum.CREATE_DOCUMENT_BY_TEXT, params, requestBody, userProvider.get().getUserId());
    }

    @Override
    public String createDocumentByFile(String datasetId, Object fileData) throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put("dataset_id", datasetId);
        return DifyApiReqUtil.sendApiReq(API_BASE_URL, API_KEY, DifyApiEnum.CREATE_DOCUMENT_BY_FILE, params, fileData, userProvider.get().getUserId());
    }


    @Override
    public String getDatasetList() throws Exception {
        return DifyApiReqUtil.sendApiReq(API_BASE_URL, API_KEY, DifyApiEnum.GET_DATASET_LIST, new HashMap<>(), null, userProvider.get().getUserId());
    }

    @Override
    public String deleteDataset(String datasetId) throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put("dataset_id", datasetId);
        return DifyApiReqUtil.sendApiReq(API_BASE_URL, API_KEY, DifyApiEnum.DELETE_DATASET, params, null, userProvider.get().getUserId());
    }

    @Override
    public String updateDocumentByText(String datasetId, String documentId, CreateDocumentReq requestBody) throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put("dataset_id", datasetId);
        params.put("document_id", documentId);
        return DifyApiReqUtil.sendApiReq(API_BASE_URL, API_KEY, DifyApiEnum.UPDATE_DOCUMENT_BY_TEXT, params, requestBody, userProvider.get().getUserId());
    }

    @Override
    public String updateDocumentByFile(String datasetId, String documentId, Object fileData) throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put("dataset_id", datasetId);
        params.put("document_id", documentId);
        // 同createDocumentByFile方法，根据实际情况处理fileData转换为请求体字符串逻辑
        String fileDataRequestBody = fileData.toString();
        return DifyApiReqUtil.sendApiReq(API_BASE_URL, API_KEY, DifyApiEnum.UPDATE_DOCUMENT_BY_FILE, params, fileDataRequestBody, userProvider.get().getUserId());
    }

    @Override
    public String getDocumentIndexingStatus(String datasetId, String batch) throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put("dataset_id", datasetId);
        params.put("batch", batch);
        return DifyApiReqUtil.sendApiReq(API_BASE_URL, API_KEY, DifyApiEnum.GET_DOCUMENT_INDEXING_STATUS, params, null, userProvider.get().getUserId());
    }

    @Override
    public String deleteDocument(String datasetId, String documentId) throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put("dataset_id", datasetId);
        params.put("document_id", documentId);
        return DifyApiReqUtil.sendApiReq(API_BASE_URL, API_KEY, DifyApiEnum.DELETE_DOCUMENT, params, null, userProvider.get().getUserId());
    }

    @Override
    public String getDatasetDocumentList(String datasetId) throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put("dataset_id", datasetId);
        return DifyApiReqUtil.sendApiReq(API_BASE_URL, API_KEY, DifyApiEnum.GET_DATASET_DOCUMENT_LIST, params, null, userProvider.get().getUserId());
    }

    @Override
    public String addDocumentSegment(String datasetId, String documentId, CreateSegmentsReq createSegmentsReq) throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put("dataset_id", datasetId);
        params.put("document_id", documentId);
        return DifyApiReqUtil.sendApiReq(API_BASE_URL, API_KEY, DifyApiEnum.ADD_DOCUMENT_SEGMENT, params, createSegmentsReq, userProvider.get().getUserId());
    }

    @Override
    public String queryDocumentSegment(String datasetId, String documentId) throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put("dataset_id", datasetId);
        params.put("document_id", documentId);
        return DifyApiReqUtil.sendApiReq(API_BASE_URL, API_KEY, DifyApiEnum.QUERY_DOCUMENT_SEGMENT, params, null, userProvider.get().getUserId());
    }

    @Override
    public String deleteDocumentSegment(String datasetId, String documentId, String segmentId) throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put("dataset_id", datasetId);
        params.put("document_id", documentId);
        params.put("segment_id", segmentId);
        return DifyApiReqUtil.sendApiReq(API_BASE_URL, API_KEY, DifyApiEnum.DELETE_DOCUMENT_SEGMENT, params, null, userProvider.get().getUserId());
    }

    @Override
    public String updateDocumentSegment(String datasetId, String documentId, String segmentId, UpdateSegmentReq obj) throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put("dataset_id", datasetId);
        params.put("document_id", documentId);
        params.put("segment_id", segmentId);
        return DifyApiReqUtil.sendApiReq(API_BASE_URL, API_KEY, DifyApiEnum.UPDATE_DOCUMENT_SEGMENT, params, obj, userProvider.get().getUserId());
    }

    @Override
    @Transactional
    public ActionResult createDifyAi(DifyAiCreateReq difyAiCreateReq) throws Exception {
        String mode = difyAiCreateReq.getMode();
        difyAiCreateReq.setMode(DifyAITypeEnum.getTypeByCode(difyAiCreateReq.getMode()));
        String token = externalLoginService.getTokenByPlatform("1");
        String response = DifyApiReqUtil.sendApiReq(DIFY_URL, "Bearer "+token, DifyApiEnum.CREATE_DIFY_AI, null,difyAiCreateReq);
        // 解析响应数据
        if (response.contains("\"id\"")) {
            // 成功响应
            ObjectMapper mapper = new ObjectMapper();
            String id = mapper.readTree(response).get("id").asText();
            AgentEntity agentEntity = new AgentEntity();
            agentEntity.setName(difyAiCreateReq.getName());
            agentEntity.setAssistantdes(difyAiCreateReq.getDescription());
            agentEntity.setCreateuserid(userProvider.get().getUserId());
            agentEntity.setCreatetime(new Date());
            agentEntity.setAiid(id);
            agentEntity.setMold(mode);
            agentService.save(agentEntity);
            return ActionResult.success(agentEntity);
        } else {
            ObjectMapper mapper = new ObjectMapper();
            String errorMsg = mapper.readTree(response).get("message").asText();
            return ActionResult.fail(errorMsg != null ? errorMsg : "创建AI失败");
        }
    }

    @Override
    public ActionResult createMetadata(CreateMetadata CreateMetadata) throws Exception {
        String token = externalLoginService.getTokenByPlatform("2");
        String response = DifyApiReqUtil.sendApiReq(RAG_URL, token, DifyApiEnum.SET_META, null, CreateMetadata);
        if (response.contains("success")) {
            return ActionResult.success("创建成功");
        } else {
            return ActionResult.fail(response);
        }
    }

    @Override
    public ActionResult getObjRelation(String dataSetId, String ragFileId) throws Exception {
        String token = externalLoginService.getTokenByPlatform("2");
        Map<String, String> params = new HashMap<>();
        params.put("dataset_id", dataSetId);
        String response = DifyApiReqUtil.sendApiReq(RAG_URL, token, DifyApiEnum.GET_OBj_IMG, params, null);
        ObjectMapper mapper = new ObjectMapper();
        try {
            // 解析完整响应
            RagGraphResponse ragGraphResponse = mapper.readValue(response, RagGraphResponse.class);
            // 判断code是否为0
            if (ragGraphResponse.getCode() == 0) {
                // 返回data对象
                return ActionResult.success(ragGraphResponse.getData());
            } else {
                // 处理失败情况
                String errorMsg = ragGraphResponse.getMessage() != null ? ragGraphResponse.getMessage() : "获取对象关系失败";
                return ActionResult.fail(errorMsg);
            }
        } catch (Exception e) {
            // 解析异常处理
            return ActionResult.fail("响应数据解析失败: " + e.getMessage());
        }
    }

    @Override
    public RagFlowApiResult createDataset(CreateKnowReq createDataSetsReq) throws Exception {
        String token = externalLoginService.getTokenByPlatform("2");
        CreateKnowReq createDataSetsReq1 = createDataSetsReq;
        createDataSetsReq1.getName();
        KnowCreate knowcreate = new KnowCreate();
        knowcreate.setName(createDataSetsReq1.getName());

        String knowCreate = DifyApiReqUtil.sendApiReq(RAG_URL, token, DifyApiEnum.CREATE_KNOW, null, knowcreate);
        ObjectMapper mapper = new ObjectMapper();
        com.fasterxml.jackson.databind.JsonNode responseNode = mapper.readTree(knowCreate);

        String kbId = responseNode.get("data").get("kb_id").asText();
        UpdateKnowReq updateKnowReq = new UpdateKnowReq();
        // 将 CreateKnowReq 的属性赋值到 UpdateKnowReq
        updateKnowReq.setKb_id(kbId);
        updateKnowReq.setName(createDataSetsReq.getName());
        updateKnowReq.setAvatar(createDataSetsReq.getAvatar());
        updateKnowReq.setDescription(createDataSetsReq.getDescription());
        updateKnowReq.setPermission(createDataSetsReq.getPermission());
        updateKnowReq.setEmbd_id(createDataSetsReq.getEmbedding_model());
        updateKnowReq.setParser_id(createDataSetsReq.getChunk_method());
        updateKnowReq.setPagerank(createDataSetsReq.getPagerank());
        updateKnowReq.setParser_config(createDataSetsReq.getParser_config());
        String knowUpdate = DifyApiReqUtil.sendApiReq(RAG_URL, token, DifyApiEnum.UPDATE_KNOW, null, updateKnowReq);
        return txtConvertObj(knowUpdate, DatasetResp.class);

    }

    @Override
    public ActionResult getModelSelectList() throws Exception {
        String token = externalLoginService.getTokenByPlatform("2");
        String response = DifyApiReqUtil.sendApiReq(RAG_URL, token, DifyApiEnum.GET_MODEL_SELECT_LIST, null, null);
        ObjectMapper mapper = new ObjectMapper();
        try {
            // 解析完整响应
            ModelListResp ragGraphResponse = mapper.readValue(response, ModelListResp.class);
            // 判断code是否为0
            if (ragGraphResponse.getCode() == 0) {
                // 返回data对象
                return ActionResult.success(ragGraphResponse.getData());
            } else {
                // 处理失败情况
                String errorMsg = ragGraphResponse.getMessage() != null ? ragGraphResponse.getMessage() : "获取模型可选列表失败";
                return ActionResult.fail(errorMsg);
            }
        } catch (Exception e) {
            // 解析异常处理
            return ActionResult.fail("响应数据解析失败: " + e.getMessage());
        }
    }

    @Override
    public RagFlowApiResult<AssistantConfigResp> saveAssistant(AssistantConfig assistantConfig) throws Exception {
        String token = externalLoginService.getTokenByPlatform("2");
        RagFlowApiResult<AssistantConfigResp> assistantConfigRespRagFlowApiResult = txtConvertObj(DifyApiReqUtil.sendApiReq(RAG_URL, token, DifyApiEnum.RAG_CREATE_HELP, null, assistantConfig), AssistantConfigResp.class);
        return assistantConfigRespRagFlowApiResult;

    }

    @Override
    public ActionResult updateDifyAi(DifyAiCreateReq difyAiCreateReq, String difyAi) throws Exception {

        difyAiCreateReq.setMode(DifyAITypeEnum.getTypeByCode(difyAiCreateReq.getMode()));

        DifyAiUpdateReq   difyAiUpdateReq = new DifyAiUpdateReq();
        difyAiUpdateReq.setName(difyAiCreateReq.getMode());
        difyAiUpdateReq.setDescription(difyAiCreateReq.getDescription());

        String token = externalLoginService.getTokenByPlatform("1");

        Map<String, String> params = new HashMap<>();
        params.put("id", difyAi);
        String response = DifyApiReqUtil.sendApiReq(DIFY_URL, "Bearer "+token, DifyApiEnum.UPDATE_DIFY_AI, params,difyAiUpdateReq);
        // 解析响应数据
        if (response.contains("\"id\"")) {
            return ActionResult.success("更新智能体成功");
        } else {
            //会出现 {"message": "Internal Server Error", "code": "unknown"}
            return ActionResult.fail("更新智能体失败:"+response);
        }
    }

    @Override
    public RagFlowApiResult<AssistantConfigResp> updateAssistant(AssistantConfigReq assistantConfig) throws Exception {
        String token = externalLoginService.getTokenByPlatform("2");
        return txtConvertObj(DifyApiReqUtil.sendApiReq(RAG_URL,token, DifyApiEnum.RAG_UPDATE_HELP, null, assistantConfig), AssistantConfigResp.class);
    }

    @Override
    public RagFlowApiResult deleteAssistant(AssistantDeleteReq assistantDeleteReq) throws Exception {
        String token = externalLoginService.getTokenByPlatform("2");
        return txtConvertObj(DifyApiReqUtil.sendApiReq(RAG_URL,token, DifyApiEnum.RAG_DELETE_HELP, null, assistantDeleteReq), AssistantConfigResp.class);
    }

    @Override
    public RagFlowApiResult deleteAssistant(AgentEntity obj) throws Exception {
        //Rag助手删除
        if(obj.getMold().equals("1")){
            AssistantDeleteReq assistantDeleteReq = new AssistantDeleteReq();
            ArrayList<String> deleteList = new ArrayList<>();
            deleteList.add(obj.getAiid());
            assistantDeleteReq.setDialog_ids(deleteList);
            String token = externalLoginService.getTokenByPlatform("2");
            return txtConvertObj(DifyApiReqUtil.sendApiReq(RAG_URL,token, DifyApiEnum.RAG_DELETE_HELP, null, assistantDeleteReq), Boolean.class);
        }else{
            //Dify助手删除
            String token = externalLoginService.getTokenByPlatform("1");
            Map<String, String> params = new HashMap<>();
            params.put("id", obj.getAiid());
            String s = DifyApiReqUtil.sendApiReq(DIFY_URL, "Bearer " + token, DifyApiEnum.DIFY_DELETE_HELP, params, null);
            //这个成功就是返回的空字符串
            RagFlowApiResult result=new RagFlowApiResult();
            if(s.equals("")){
                result.setCode(0);
            }else{
                result.setCode(500);
                result.setMessage("删除Dify知识库失败:"+s);
            }
            return result;
        }
    }

    @Override
    public ActionResult getKnowSelect() {
        // 查询know_mange表的F_Id和name字段（假设KnowMangeEntity包含这两个字段）
        QueryWrapper<KnowMangeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("F_Id as ID","NAME","DATASETID");
        List<KnowMangeEntity> result = knowMangeService.list(queryWrapper);

        return ActionResult.success(result);
    }
}
